package io.renren.modules.sys.controller;

import io.renren.common.imp.JxStudentImp;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.entity.JxStudentEntity;
import io.renren.modules.sys.service.JxStudentService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 学生表
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2021-10-06 14:13:49
 */
@RestController
@RequestMapping("sys/jxstudent")
public class JxStudentController {
    @Autowired
    private JxStudentService jxStudentService;
    @Autowired
    private JxStudentImp jxStudentImp;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:jxstudent:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = jxStudentService.getAllWithPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:jxstudent:info")
    public R info(@PathVariable("id") Long id) {
        JxStudentEntity jxStudent = jxStudentService.getById(id);

        return R.ok().put("jxStudent", jxStudent);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:jxstudent:save")
    public R save(@RequestBody JxStudentEntity jxStudent) {
        jxStudent.setIcon(JxStudentEntity.DEFIND_ICON);
        ValidatorUtils.validateEntity(jxStudent, AddGroup.class);
        jxStudentService.saveStudent(jxStudent);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:jxstudent:update")
    public R update(@RequestBody JxStudentEntity jxStudent) {
        ValidatorUtils.validateEntity(jxStudent,UpdateGroup.class);
        jxStudent.setUpdateTime(new Date());
        jxStudentService.updateById(jxStudent);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:jxstudent:delete")
    public R delete(@RequestBody Long[] ids) {
        jxStudentService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 批量导入
     */
    //导入
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public R importExcel(@RequestParam("file") MultipartFile file, Long classId, Long schoolId) throws IOException, Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<>();
        param.put("classId", classId);
        param.put("schoolId", schoolId);
        if (!((classId + schoolId) > 0)) {
            return R.error(500, "请选择学校班级");
        }
        if(file==null){
            return R.error(500, "请选择您要导入的文件");
        }else{
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if(!suffix.equals(".xls")){
                return R.error(500, "请导入xls 格式文件");
            }
        }
        try {
            map = jxStudentImp.importExcel(file, param);
            return R.error(Integer.parseInt(map.get("code").toString()), map.get("msg").toString());
        } catch (Exception e) {
            return R.error(500, "发生未知异常");
        }


    }


    @ApiOperation("下载模板")
    @RequestMapping(value = "/downModel",method = RequestMethod.GET,produces="application/json")
    public R downModel(HttpServletResponse response, HttpServletRequest request) {
        String fileName = request.getParameter("fileName");
        ServletOutputStream out;
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        try{
            String filePath = getClass().getResource("/statics/template/" + fileName).getPath();//文件在项目中的存放路径
            String userAgent = request.getHeader("User-Agent");
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                // 非IE浏览器的处理：
                fileName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");
            }
            filePath = URLDecoder.decode(filePath, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            FileInputStream inputStream = new FileInputStream(filePath);
            out = response.getOutputStream();
            int b = 0;
            byte[] buffer = new byte[1024];
            while ((b = inputStream.read(buffer)) != -1) {
                // 4.写到输出流(out)中
                out.write(buffer, 0, b);
            }
            inputStream.close();

            if (out != null) {
                out.flush();
                out.close();
            }
        }catch (Exception e){
            return  R.error("数据异常");
        }
        return null;
    }


}
